<template>
  <div class="admin-exhibitors">
    <div class="page-header">
      <h2>展商管理</h2>
      <div class="header-actions">
        <el-button v-if="hasPermission('exhibitor_add')" type="primary" @click="addExhibitor">
          添加展商
        </el-button>
        <el-button v-if="hasPermission('exhibitor_import')" type="primary" @click="handleImport">导入</el-button>

      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.keyword" placeholder="搜索公司名称/联系人" clearable @input="handleSearch" />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="审核状态" clearable @change="handleSearch">
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.industry" placeholder="行业分类" clearable @change="handleSearch">
            <el-option label="机器人核心零部件（含成熟和创新产品）" value="机器人核心零部件（含成熟和创新产品）" />
            <el-option label="大脑相关（人工智能算法及其他）" value="大脑相关（人工智能算法及其他）" />
            <el-option label="整机研发、设计、系统集成" value="整机研发、设计、系统集成" />
            <el-option label="机器人检测、维修和保养、测试验证等" value="机器人检测、维修和保养、测试验证等" />
            <el-option label="机器人生产设备、流水线、代工厂等" value="机器人生产设备、流水线、代工厂等" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button @click="exportExcel">导出</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 展商列表 -->
    <el-table :data="exhibitorsList" border stripe v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="companyName" label="公司" min-width="200" />
      <el-table-column prop="contactPerson" label="联系人" width="120" />
      <el-table-column prop="boothRequirements" label="职务" width="120" />
      <el-table-column prop="contactPhone" label="联系方式" width="130" />
      <!-- <el-table-column prop="contactEmail" label="联系邮箱" width="180" /> -->
      <el-table-column prop="companyAddress" label="地址" min-width="200" />
      <el-table-column prop="boothNumber" label="展位号" width="100" />
      <el-table-column prop="industryType" label="行业分类" width="200">
        <template #default="scope">
          {{ scope.row.industryType || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="审核状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="申请时间" width="160" />
      <el-table-column label="操作" width="260" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewExhibitor(scope.row)">查看</el-button>
          <el-button v-if="hasPermission('exhibitor_edit')" size="small" type="primary"
            @click="editExhibitor(scope.row)">
            编辑
          </el-button>
          <el-button v-if="hasPermission('exhibitor_approve') && scope.row.status === 'pending'" size="small"
            type="success" @click="approveExhibitor(scope.row)">
            审核
          </el-button>
          <el-button v-if="hasPermission('exhibitor_delete')" size="small" type="danger"
            @click="deleteExhibitor(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 添加/编辑展商对话框 -->
    <el-dialog v-model="showAddDialog" :title="editingExhibitor ? '编辑展商' : '添加展商'" width="600px">
      <el-form :model="exhibitorForm" :rules="exhibitorRules" ref="exhibitorFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="exhibitorForm.companyName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="exhibitorForm.contactPerson" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职务" prop="boothRequirements">
              <el-input v-model="exhibitorForm.boothRequirements" placeholder="联系人职务" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model="exhibitorForm.contactPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="exhibitorForm.contactEmail" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="companyAddress">
              <el-input v-model="exhibitorForm.companyAddress" placeholder="公司详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="展位号" prop="boothNumber">
              <el-input v-model="exhibitorForm.boothNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="展品范围" prop="industryType">
              <el-select v-model="exhibitorForm.industryType" placeholder="选择展品范围">
                <el-option label="机器人核心零部件（含成熟和创新产品）" value="机器人核心零部件（含成熟和创新产品）" />
                <el-option label="大脑相关（人工智能算法及其他）" value="大脑相关（人工智能算法及其他）" />
                <el-option label="整机研发、设计、系统集成" value="整机研发、设计、系统集成" />
                <el-option label="机器人检测、维修和保养、测试验证等" value="机器人检测、维修和保养、测试验证等" />
                <el-option label="机器人生产设备、流水线、代工厂等" value="机器人生产设备、流水线、代工厂等" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="公司Logo" prop="logoUrl">
          <div class="image-upload-container">
            <el-upload class="image-uploader" :action="uploadAction" :headers="uploadHeaders"
              :data="{ type: 'exhibitor' }" :show-file-list="false" :on-success="handleLogoSuccess"
              :on-error="handleImageError" :before-upload="beforeImageUpload" accept="image/*">
              <img v-if="exhibitorForm.logoUrl" :src="exhibitorForm.logoUrl" class="uploaded-image" />
              <el-icon v-else class="image-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
            <el-input v-model="exhibitorForm.logoUrl" placeholder="或直接输入Logo URL" style="margin-top: 10px;" />
          </div>
        </el-form-item>
        <el-form-item label="公司简介" prop="companyDescription">
          <el-input v-model="exhibitorForm.companyDescription" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="exhibitorForm.status">
            <el-radio label="pending">待审核</el-radio>
            <el-radio label="approved">已通过</el-radio>
            <el-radio label="rejected">已拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveExhibitor" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 查看展商详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="查看展商详情" width="600px">
      <div v-if="viewingExhibitor" class="exhibitor-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="公司名称">{{ viewingExhibitor.companyName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ viewingExhibitor.contactPerson || '-' }}</el-descriptions-item>
          <el-descriptions-item label="职务">{{ viewingExhibitor.boothRequirements || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ viewingExhibitor.contactPhone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系邮箱">{{ viewingExhibitor.contactEmail || '-' }}</el-descriptions-item>
          <el-descriptions-item label="展位号">{{ viewingExhibitor.boothNumber || '-' }}</el-descriptions-item>
          <el-descriptions-item label="行业分类">{{ viewingExhibitor.industryType || '-' }}</el-descriptions-item>
          <el-descriptions-item label="公司地址" :span="2">{{ viewingExhibitor.companyAddress || '-'
          }}</el-descriptions-item>
          <el-descriptions-item label="公司网站">{{ viewingExhibitor.companyWebsite || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(viewingExhibitor.status)">
              {{ getStatusText(viewingExhibitor.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ viewingExhibitor.createdTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="公司描述" :span="2">{{ viewingExhibitor.companyDescription || '-'
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { exhibitorApi } from '@/api/admin'
import request from '@/utils/request'
import config from '@/config'
import { useExcelExport, importFromExcel } from '@/hooks/useExcelExport'

export default {
  name: 'AdminExhibitors',
  components: {
    Plus
  },
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const showAddDialog = ref(false)
    const editingExhibitor = ref(null)
    const viewDialogVisible = ref(false)
    const viewingExhibitor = ref(null)

    // 使用Excel导出hooks
    const { exportListData, columnWidthPresets, mapperPresets } = useExcelExport()

    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      status: '',
      industry: ''
    })

    // 展商表单
    const exhibitorForm = reactive({
      companyName: '',
      contactPerson: '',
      boothRequirements: '',
      contactPhone: '',
      contactEmail: '',
      companyAddress: '',
      boothNumber: '',
      industryType: '',
      logoUrl: '',
      companyDescription: '',
      status: 'pending'
    })

    // 表单验证规则
    const exhibitorRules = {
      companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
      contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
      contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
      contactEmail: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      companyAddress: [{ required: true, message: '请输入地址', trigger: 'blur' }],
      industryType: [{ required: true, message: '请选择展品范围', trigger: 'change' }]
    }

    // 分页
    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    // 展商列表
    const exhibitorsList = ref([])

    // 图片上传配置
    const apiConfig = config.getApiConfig()
    const uploadAction = ref(`${apiConfig.baseURL}/api/upload/image`)
    const uploadHeaders = ref({
      'token': localStorage.getItem('adminToken') || ''
    })

    // 权限检查
    const hasPermission = (permission) => {
      // 这里应该根据实际权限系统实现
      return true
    }

    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case 'pending':
          return 'warning'
        case 'approved':
          return 'success'
        case 'rejected':
          return 'danger'
        default:
          return 'info'
      }
    }

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'pending':
          return '待审核'
        case 'approved':
          return '已通过'
        case 'rejected':
          return '已拒绝'
        default:
          return status
      }
    }

    // 获取行业文本
    const getIndustryText = (industry) => {
      return industry || '-'
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadExhibitors()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        keyword: '',
        status: '',
        industry: ''
      })
      handleSearch()
    }

    // 加载展商数据
    const loadExhibitors = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.current,
          size: pagination.size,
          status: searchForm.status || '',
          industryType: searchForm.industry || '',
          companyName: searchForm.keyword || ''
        }

        const response = await exhibitorApi.getExhibitorPage(params)
        if (response.code === '200') {
          exhibitorsList.value = response.data.records || []
          pagination.total = response.data.total || 0
        }
      } catch (error) {
        console.error('加载展商数据失败:', error)
        ElMessage.error('加载展商数据失败')
      } finally {
        loading.value = false
      }
    }

    // 查看展商
    const viewExhibitor = async (row) => {
      try {
        const res = await request.get(`/admin/exhibitor/${row.id}`)
        if (res && (res.code === '200' || res.code === 200)) {
          viewingExhibitor.value = res.data
          viewDialogVisible.value = true
        } else {
          ElMessage.error(res?.msg || '获取展商详情失败')
        }
      } catch (e) {
        ElMessage.error('获取展商详情失败')
      }
    }

    // 添加展商
    const addExhibitor = () => {
      editingExhibitor.value = null
      Object.assign(exhibitorForm, {
        companyName: '',
        contactPerson: '',
        boothRequirements: '',
        contactPhone: '',
        contactEmail: '',
        companyAddress: '',
        boothNumber: '',
        industryType: '',
        logoUrl: '',
        companyDescription: '',
        status: 'pending'
      })
      showAddDialog.value = true
    }

    // 编辑展商
    const editExhibitor = (row) => {
      editingExhibitor.value = row
      Object.assign(exhibitorForm, { ...row })
      showAddDialog.value = true
    }

    // 审核展商
    const approveExhibitor = async (row) => {
      try {
        await ElMessageBox.confirm('确定要通过这个展商申请吗？', '确认审核', {
          type: 'warning'
        })

        const response = await exhibitorApi.auditExhibitor(row.id, 'approved', '审核通过', 'admin')
        if (response.code === '200') {
          ElMessage.success('审核成功')
          loadExhibitors()
        } else {
          ElMessage.error(response.msg || '审核失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('审核失败')
        }
      }
    }

    // 删除展商
    const deleteExhibitor = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个展商吗？', '确认删除', {
          type: 'warning'
        })

        const response = await exhibitorApi.deleteExhibitor(row.id)
        if (response.code === '200') {
          ElMessage.success('删除成功')
          loadExhibitors()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 图片上传相关方法
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 15

      if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 15MB!')
        return false
      }
      return true
    }

    const handleLogoSuccess = (response) => {
      if (response && response.code === '200' && response.data) {
        exhibitorForm.logoUrl = response.data.url
        ElMessage.success('Logo上传成功')
      } else {
        ElMessage.error('Logo上传失败')
      }
    }

    const handleImageError = () => {
      ElMessage.error('图片上传失败')
    }

    // 保存展商
    const saveExhibitor = async () => {
      saving.value = true
      try {
        let response
        if (editingExhibitor.value) {
          response = await exhibitorApi.updateExhibitor(exhibitorForm)
        } else {
          response = await exhibitorApi.addExhibitor(exhibitorForm)
        }

        if (response.code === '200') {
          ElMessage.success(editingExhibitor.value ? '更新成功' : '添加成功')
          showAddDialog.value = false
          editingExhibitor.value = null
          Object.assign(exhibitorForm, {
            companyName: '',
            contactPerson: '',
            contactPhone: '',
            contactEmail: '',
            boothNumber: '',
            industryType: '',
            logoUrl: '',
            companyDescription: '',
            status: 'pending'
          })
          loadExhibitors()
        } else {
          ElMessage.error(response.msg || '保存失败')
        }
      } catch (error) {
        ElMessage.error('保存失败: ' + (error.message || '未知错误'))
      } finally {
        saving.value = false
      }
    }



    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      loadExhibitors()
    }

    const handleCurrentChange = (current) => {
      pagination.current = current
      loadExhibitors()
    }

    // 导出展商列表
    const exportExcel = async () => {
      // 获取数据的函数
      const fetchData = async () => {
        const params = {
          page: 1,
          size: 1000000,
          status: searchForm.status || '',
          industryType: searchForm.industry || '',
          companyName: searchForm.keyword || ''
        }
        const response = await exhibitorApi.getExhibitorPage(params)
        return response.data.records
      }

      // 数据映射函数
      const mapData = (item) => ({
        '公司名称': mapperPresets.handleEmpty(item.companyName),
        '联系人': mapperPresets.handleEmpty(item.contactPerson),
        '职务': mapperPresets.handleEmpty(item.boothRequirements),
        '联系电话': mapperPresets.handleEmpty(item.contactPhone),
        '联系邮箱': mapperPresets.handleEmpty(item.contactEmail),
        '展位号': mapperPresets.handleEmpty(item.boothNumber),
        '行业分类': mapperPresets.handleEmpty(item.industryType),
        '公司地址': mapperPresets.handleEmpty(item.companyAddress),
        '公司网站': mapperPresets.handleEmpty(item.companyWebsite),
        '审核状态': getStatusText(item.status),
        '申请时间': mapperPresets.handleEmpty(item.createdTime),
        '公司描述': mapperPresets.handleEmpty(item.companyDescription)
      })

      // 使用hooks进行导出
      await exportListData(
        fetchData,
        mapData,
        '展商列表',
        columnWidthPresets.exhibitor,
        '展商列表'
      )
    }

    // 导入展商列表
    const handleImport = () => {
      const headerMap = {
        '公司名称': 'companyName',
        '联系人': 'contactPerson',
        '职务': 'boothRequirements',
        '联系方式': 'contactPhone',
        '联系邮箱': 'contactEmail',
        '地址': 'companyAddress',
        '展品范围': 'industryType',
        '公司简介': 'companyDescription'
      }

      const processData = async (data) => {
        loading.value = true
        let successCount = 0
        let failCount = 0

        for (const item of data) {
          try {
            await exhibitorApi.addExhibitor(item)
            successCount++
          } catch (error) {
            console.error('导入失败:', item, error)
            failCount++
          }
        }

        loading.value = false
        ElMessage.success(`导入完成！成功 ${successCount} 条，失败 ${failCount} 条。`)
        loadExhibitors()
      }

      importFromExcel(headerMap, processData)
    }


    onMounted(() => {
      loadExhibitors()
    })

    return {
      loading,
      saving,
      showAddDialog,
      editingExhibitor,
      viewDialogVisible,
      viewingExhibitor,
      searchForm,
      exhibitorForm,
      exhibitorRules,
      pagination,
      exhibitorsList,
      uploadAction,
      uploadHeaders,
      hasPermission,
      getStatusType,
      getStatusText,
      getIndustryText,
      handleSearch,
      resetSearch,
      viewExhibitor,
      addExhibitor,
      editExhibitor,
      approveExhibitor,
      deleteExhibitor,
      saveExhibitor,
      handleSizeChange,
      handleCurrentChange,
      beforeImageUpload,
      handleLogoSuccess,
      handleImageError,
      exportExcel,
      handleImport
    }
  }
}
</script>

<style scoped>
.admin-exhibitors {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}


/* 图片上传样式 */
.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 120px;
  height: 80px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>